ReactJS Ultra For Beginners

🔄 React Component Lifecycle


What is Component Lifecycle?

  • The sequence of events that occur during a component's existence
  • From creation (mounting) to destruction (unmounting)
  • Includes updates when props or state change
  • Understanding lifecycle helps optimize performance and manage side effects

📝 Lifecycle Phases

1. Mounting Phase:

  • Component is created and inserted into the DOM
  • constructor() → render() → componentDidMount()

2. Updating Phase:

  • Component re-renders due to props or state changes
  • render() → componentDidUpdate()

3. Unmounting Phase:

  • Component is removed from the DOM
  • componentWillUnmount()

🔑 Class Component Lifecycle

Mounting:

class UserProfile extends React.Component { constructor(props) { super(props); this.state = { user: null, loading: true, }; console.log("1. Constructor called"); } componentDidMount() { console.log("3. Component mounted"); // Perfect place for API calls, subscriptions this.fetchUser(); } fetchUser = async () => { try { const user = await fetchUserAPI(this.props.userId); this.setState({ user, loading: false }); } catch (error) { console.error("Error fetching user:", error); } }; render() { console.log("2. Render called"); const { user, loading } = this.state; if (loading) return <div>Loading...</div>; if (!user) return <div>User not found</div>; return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> ); } }

Updating:

class UserProfile extends React.Component { componentDidUpdate(prevProps, prevState) { console.log("Component updated"); // Check if userId changed if (prevProps.userId !== this.props.userId) { this.fetchUser(); } // Check if user state changed if (prevState.user !== this.state.user) { console.log("User data updated"); } } shouldComponentUpdate(nextProps, nextState) { // Optimize re-renders return ( this.props.userId !== nextProps.userId || this.state.user !== nextState.user || this.state.loading !== nextState.loading ); } render() { // Render logic } }

Unmounting:

class UserProfile extends React.Component { constructor(props) { super(props); this.state = { user: null }; this.subscription = null; } componentDidMount() { // Subscribe to user updates this.subscription = userService.subscribe(this.props.userId, (user) => { this.setState({ user }); }); } componentWillUnmount() { console.log("Component will unmount"); // Clean up subscriptions, timers, event listeners if (this.subscription) { this.subscription.unsubscribe(); } } render() { // Render logic } }

🎯 Functional Component Lifecycle

Using useEffect for Lifecycle:

import { useState, useEffect } from "react"; function UserProfile({ userId }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); // componentDidMount equivalent useEffect(() => { console.log("Component mounted"); fetchUser(); }, []); // Empty dependency array = run only once // componentDidUpdate equivalent useEffect(() => { console.log("userId changed, fetching new user"); if (userId) { fetchUser(); } }, [userId]); // Run when userId changes // componentWillUnmount equivalent useEffect(() => { return () => { console.log("Component will unmount"); // Cleanup function }; }, []); const fetchUser = async () => { try { setLoading(true); const userData = await fetchUserAPI(userId); setUser(userData); } catch (error) { console.error("Error fetching user:", error); } finally { setLoading(false); } }; if (loading) return <div>Loading...</div>; if (!user) return <div>User not found</div>; return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> ); }

🔧 Advanced Lifecycle Patterns

Subscription Management:

function RealTimeUser({ userId }) { const [user, setUser] = useState(null); useEffect(() => { // Set up subscription const subscription = userService.subscribe(userId, (userData) => { setUser(userData); }); // Cleanup subscription on unmount or userId change return () => { subscription.unsubscribe(); }; }, [userId]); return user ? <div>{user.name}</div> : <div>Loading...</div>; }

Timer Management:

function Timer() { const [count, setCount] = useState(0); useEffect(() => { const interval = setInterval(() => { setCount((prev) => prev + 1); }, 1000); // Cleanup timer on unmount return () => { clearInterval(interval); }; }, []); // Empty array = run only once return <div>Count: {count}</div>; }

Event Listener Management:

function WindowResize() { const [windowSize, setWindowSize] = useState({ width: window.innerWidth, height: window.innerHeight, }); useEffect(() => { const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); }; window.addEventListener("resize", handleResize); // Cleanup event listener return () => { window.removeEventListener("resize", handleResize); }; }, []); // Empty array = run only once return ( <div> Window size: {windowSize.width} x {windowSize.height} </div> ); }

🎯 Performance Optimization

Memoization with useMemo:

function ExpensiveComponent({ items, filter }) { // Memoize expensive calculation const filteredItems = useMemo(() => { console.log("Filtering items..."); return items.filter((item) => item.name.includes(filter)); }, [items, filter]); // Recalculate only when items or filter change return ( <ul> {filteredItems.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> ); }

Callback Memoization:

function ParentComponent() { const [count, setCount] = useState(0); // Memoize callback to prevent child re-renders const handleClick = useCallback(() => { console.log("Button clicked"); }, []); // Empty array = callback never changes return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> <ChildComponent onButtonClick={handleClick} /> </div> ); } // Child component will only re-render when props actually change const ChildComponent = React.memo(({ onButtonClick }) => { console.log("Child component rendered"); return <button onClick={onButtonClick}>Click me</button>; });

⚠️ Common Pitfalls

1. Missing Dependencies:

// ❌ Bad - missing dependency useEffect(() => { fetchUser(userId); }, []); // userId not in dependency array // ✅ Good - include all dependencies useEffect(() => { fetchUser(userId); }, [userId]);

2. Infinite Re-renders:

// ❌ Bad - causes infinite re-renders useEffect(() => { setCount(count + 1); }, [count]); // ✅ Good - use functional update useEffect(() => { setCount((prev) => prev + 1); }, []); // Or use useCallback for the function

3. Memory Leaks:

// ❌ Bad - potential memory leak useEffect(() => { const subscription = api.subscribe((data) => setData(data)); // Missing cleanup }, []); // ✅ Good - proper cleanup useEffect(() => { const subscription = api.subscribe((data) => setData(data)); return () => subscription.unsubscribe(); }, []);

🔄 Lifecycle Comparison

Class vs Functional:

| Class Component | Functional Component | | ------------------------- | ------------------------------------------ | | constructor() | useState() initialization | | componentDidMount() | useEffect(() => {}, []) | | componentDidUpdate() | useEffect(() => {}, [deps]) | | componentWillUnmount() | useEffect(() => { return cleanup; }, []) | | shouldComponentUpdate() | React.memo() or useMemo() |


🎯 Best Practices

  1. Use functional components - they're simpler and more performant
  2. Always clean up - subscriptions, timers, event listeners
  3. Include all dependencies - in useEffect dependency arrays
  4. Optimize re-renders - use React.memo, useMemo, useCallback
  5. Handle loading states - provide feedback during async operations
  6. Test lifecycle behavior - ensure cleanup works correctly